﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XStudio.XCRF.Data.Business;
using XStudio.XCRF.Data.Business.Permissions;
using XStudio.XCRF.Data.Entities;
using XStudio.XCRF.Data.Enums;
using XStudio.XCRF.Utilities.Base64Encryption;
using XStudio.XCRF.Utilities.MD5Encryption;
using XStudio.XCRF.Web.Common.Sessions;
using XStudio.XCRF.Web.Models.Enums;
using XStudio.XCRF.Web.Models.Member;
using Telerik.Web.Mvc;

namespace XStudio.XCRF.Web.Controllers
{
    /// <summary>
    /// 成员控制器
    /// </summary>
    public partial class MemberController : BaseController
    {
        /// <summary>
        /// 处理登陆页面请求
        /// </summary>
        /// <param name="backUrl">回跳URL</param>
        /// <returns></returns>
        [AllowAnonymousCall]
        public ActionResult MemberLogin()
        {
            if (IsLoggedIn)
                return RedirectToAction<HomeController>(c => c.Index());
            else return View();
        }

        /// <summary>
        /// 处理登陆系统POST请求
        /// </summary>
        /// <param name="member">登录用户信息</param>
        /// <returns></returns>
        [AllowAnonymousCall]
        [HttpPost]
        public JsonResult MemberLogin(Member member)
        {
            bool bResult = false;
            String error = "";
            if (IsLoggedIn)
                bResult = true;
            else
            {
                try
                {
                    Member member_db = ((IQueryable<Member>)DataContext.Members).Find(member.LoginName);
                    if (member_db.PasswordMD5 == member.PasswordMD5)
                    {
                        LoginSession.LogIn(member_db);
                        bResult = true;
                    }
                }
                catch (Exception e) { bResult = false; error = e.InnerException.Message; }
            }
            var result = new { success = bResult , error = error };
            return Json(result);
        }

        /// <summary>
        /// 处理注销登录系统请求
        /// </summary>
        /// <returns></returns>
        [AllowAnonymousCall]
        public ActionResult Logout()
        {
            if (IsLoggedIn)
                LoginSession.LogOut();
            return RedirectToAction<HomeController>(c => c.Index());
        }

        /// <summary>
        /// 当访问无权限时跳转
        /// </summary>
        /// <returns></returns>
        [AllowAnonymousCall]
        public ActionResult NoPermission()
        {
            return View();
        }

        /// <summary>
        /// 处理添加成员页面请求
        /// </summary>
        /// <param name="hospitalID">医院ID，可省略默认为当前登录医院</param>
        /// <param name="type">用户类型</param>
        /// <returns></returns>
        [AllowMemberType(MemberTypes.Administrator | MemberTypes.Owner)]
        public ActionResult MemberAdd(byte type, Guid? hospitalID)
        {
            switch (type)
            {
                case (byte)MemberTypes.Owner: break;
                case (byte)MemberTypes.Researcher: break;
                case (byte)MemberTypes.Administrator:
                default:
                    type = (byte)MemberTypes.Researcher;
                    break;
            }
            if (hospitalID == null)
                hospitalID = HospitalID;
            Hospital hospital = DataContext.Hospitals.Find((Guid)hospitalID);
            MemberTypes loginType = LoginType.Value;
            if (loginType == MemberTypes.Administrator
              || (loginType == MemberTypes.Owner && HospitalID == hospitalID))
            {
                Member member = new Member
                {
                    HospitalID = (Guid)hospitalID,
                    Hospital = hospital,
                    Type = type
                };
                return View(member);
            }
            else
            {
                return RedirectToAction<MemberController>(c => c.NoPermission());
            }
        }

        /// <summary>
        /// 处理添加用户的POST请求
        /// </summary>
        /// <param name="member">欲添加的用户</param>
        /// <returns></returns>
        [AllowMemberType(MemberTypes.Administrator | MemberTypes.Owner)]
        [HttpPost]
        public JsonResult MemberAdd(Member member)
        {
            try
            {
                MemberTypes loginType = LoginType.Value;
                Guid hospitalID = member.HospitalID;
                if (loginType == MemberTypes.Administrator
                  || (loginType == MemberTypes.Owner && HospitalID == hospitalID))
                {
                    member.Hospital = null;
                    DataContext.Members.Add(member);
                    DataContext.SaveChanges();
                    //return Json(member);
                    return Json(new { ID = member.ID });
                }
                else
                {
                    throw new Exception("无权限操作");
                }
            }
            catch
            {
                return Json(null);
            }
        }

        /// <summary>
        /// 处理查看成员详细信息的页面请求
        /// </summary>
        /// <param name="memberID">成员ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult MemberDetail(Guid? memberID)
        {
            if (memberID == null)
                memberID = LoginID;
            Member member = ((IQueryable<Member>)DataContext.Members).Find((Guid)memberID);
            return View(member);
        }

        /// <summary>
        /// 处理编辑成员信息的页面请求
        /// </summary>
        /// <param name="memberID">成员ID</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        public ActionResult MemberEdit(Guid? memberID)
        {
            if (memberID == null)
                memberID = LoginID;
            Member member = ((IQueryable<Member>)DataContext.Members).Find((Guid)memberID);
            return View(member);
        }

        /// <summary>
        /// 处理编辑成员请求
        /// </summary>
        /// <param name="member">更新信息</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [DefaultPermission(PermissionType.Allow)]
        [HttpPost]
        public JsonResult MemberEdit(Member member)
        {
            try
            {
                Member member_db = DataContext.Members.Find(member.ID);
                if (member_db.PasswordMD5 != member.PasswordMD5)
                    throw new Exception("密码错误");
                member_db.RealName = member.RealName;
                member_db.Gender = member.Gender;
                member_db.Phone = member.Phone;
                member_db.Email = member.Email;
                member_db.Profile = member.Profile;
                DataContext.SaveChanges();
                //如果修改的是当前自己登录的用户，则强制刷新登录
                if (member_db.ID == LoginID)
                {
                    LoginSession.LogOut();
                    LoginSession.LogIn(member_db);
                }
                return Json(new { ID = member_db.ID });
            }
            catch
            {
                return Json(null);
            }
        }

        /// <summary>
        /// 处理删除成员的POST请求
        /// </summary>
        /// <param name="memberID">要删除的成员ID</param>
        /// <returns></returns>
        [AllowMemberType(MemberTypes.Administrator)]
        [HttpPost]
        public JsonResult MemberDelete(Guid memberID)
        {
            bool bResult;
            try
            {
                Member member = DataContext.Members.Find(memberID);
                DataContext.Members.Remove(member);
                DataContext.SaveChanges();
                bResult = true;
            }
            catch { bResult = false; }
            var result = new { success = bResult };
            return Json(result);
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult MemberEditSelf()
        {
            Member member = DataContext.CurrentMember;
            return View(member);
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult MemberDetailSelf()
        {
            Member member = DataContext.CurrentMember;
            return View(member);
        }

        [DefaultPermission(PermissionType.Allow)]
        public ActionResult MemberChangePasswordSelf()
        {
            return View();
        }

        [DefaultPermission(PermissionType.Allow)]
        [HttpPost]
        public ActionResult _MemberChangePasswordSelf(MemberChangePasswordDTO dto)
        {
            try
            {
                Member member = DataContext.CurrentMember;
                if (!dto.IsValid)
                    throw new Exception("新密码不一致");
                if (member.PasswordMD5 != dto.OldPasswordMD5)
                    throw new Exception("旧密码错误");
                member.PasswordMD5 = dto.NewPasswordMD51;
                DataContext.SaveChanges();
                LoginSession.LogOut();
                return Json(new { ID = member.ID });
            }
            catch
            {
                return Json(null);
            }
        }

        [DefaultPermission(PermissionType.Allow)]
        [GridAction]
        [HttpPost]
        public ActionResult _MemberDelete(Member member)
        {
            Member member_db = ((IQueryable<Member>)DataContext.Members).Find(member.ID);
            Guid hospitalID = member_db.HospitalID;
            DataContext.Members.Remove(member_db);
            if (member_db.Type == (byte)MemberTypes.Owner)
                throw new Exception("不能手动删除医院主管");
            DataContext.SaveChanges();
            List<Member> members = ((IQueryable<Member>)DataContext.Members)
                .Find(m => m.HospitalID == hospitalID).ToList();
            List<Member> dtos = (from m in members
                                 select new Member
                                 {
                                     ID = m.ID,
                                     LoginName = m.LoginName,
                                     RealName = m.RealName,
                                     Gender = m.Gender,
                                     Type = m.Type
                                 }).ToList();
            GridModel<Member> data = new GridModel<Member>(dtos);
            return Json(data);
        }
    }
}
